<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.categoryId" placeholder="类目ID，必须是整数"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.productNo" placeholder="商品编号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.name" placeholder="商品名称，模糊查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filters.isDisplay" clearable placeholder="是否已上架" style="width:120px">
            <el-option
              v-for="item in displayOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="handleFilter">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table
      :data="list"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%;"
    >
      <el-table-column prop="productId" type="selection" width="60"></el-table-column>
      <el-table-column prop="productNo" label="商品编码" width="120"></el-table-column>
      <el-table-column prop="categoryId" label="类目ID" width="120"></el-table-column>
      <!--
				<el-table-column prop="productNo" label="productNo" width="120" sortable>
			</el-table-column>
      -->
      <el-table-column prop="title" label="标题描述" width="160"></el-table-column>
      <el-table-column prop="mainImage" label="主图案" width="80">
        <template slot-scope="scope">
          <img
            :src="scope.row.mainImage"
            width="60"
            @click="showMainImg(scope.row.mainImage)"
            title="点击查看大图"
            alt="没有配置主图案"
          >
        </template>
      </el-table-column>
      <el-table-column prop="subImage" label="副图片" width="120">
        <template slot-scope="scope">
          <a @click="showSubImg(scope.row.subImage)" v-if="scope.row.subImage">点击查看</a>
          <span v-if="!scope.row.subImage">尚未配置</span>
        </template>
      </el-table-column>
      <el-table-column label="特性" min-width="180">
        <template slot-scope="scope">
          <p
            style="margin: 0;"
            v-for="(item,index) in scope.row.attribute"
            :key="index"
          >{{index +':' + item}}</p>
          <!-- <p style="margin: 0;" v-if="scope.row.attribute['口味']"> 口味：{{scope.row.attribute["口味"]}}</p>
          <p style="margin: 0;" v-if="scope.row.attribute['包装']"> 包装：{{scope.row.attribute["包装"]}}</p>-->
        </template>
      </el-table-column>
      <el-table-column label="是否已上架" min-width="180">
        <template slot-scope="scope">
          <span>{{0==scope.row.isDisplay?"下架":"上架"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上架时间" min-width="120" sortable></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :page-size="20"
        :total="total"
        style="float:right;"
      ></el-pagination>
    </el-col>

    <el-dialog title="查看主图片" v-model="mainImgFormVisible" :close-on-click-modal="false">
      <img :src="mainImgSrc" alt="加载失败">
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="mainImgFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看副图片" v-model="subImgFormVisible" :close-on-click-modal="false">
      <div>
        <el-carousel>
          <el-carousel-item v-for="item in subImgSrc" :key="item">
            <img :src="item" alt="加载失败">
          </el-carousel-item>
        </el-carousel>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="subImgFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" class="form_input"></el-input>
        </el-form-item>
        <el-form-item label="标题" prop="subTitle">
          <el-input v-model="addForm.subTitle" auto-complete="off" class="form_input"></el-input>
        </el-form-item>
        <el-form-item label="图片上传" prop="images">
          <el-upload
            action="https://wx.hulupi.com/cityfood/upload"
            multiple
            accept="image/png, image/jpeg"
            list-type="picture-card"
            :before-upload="beforeUploadPicture"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-progress="uploadProgress"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="addForm.categoryId" placeholder="请选择类别" @change="currentSel">
            <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="2" style="width:120px">
            <div class="sub-title">商品特性：</div>
          </el-col>
          <el-col :span="20">
            <el-row :gutter="10" v-for="(item,index) in addForm.categoryKeys" :key="index">
              <el-col :span="6">
                <el-form-item :label="item.value">
                  <el-select
                    style="width:180px"
                    v-model="addForm.productAttrs[item.value]"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请添加属性描述信息"
                  ></el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="4"></el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-form-item label="商品详情" prop="detail">
          <el-input v-model="addForm.detail" auto-complete="off" class="form_input"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--编辑界面-->
    <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品ID" prop="productId">
              <el-input v-model="editForm.productId" readonly class="form_input"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="editForm.name" auto-complete="off" class="form_input"></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="subTitle">
              <el-input v-model="editForm.subTitle" auto-complete="off" class="form_input"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="images">
              <el-upload
                action="https://wx.hulupi.com/cityfood/upload"
                multiple
                accept="image/png, image/jpeg"
                list-type="picture-card"
                :before-upload="beforeUploadPicture"
                :on-preview="handlePictureCardPreview"
                :on-remove="editHandleRemove"
                :on-progress="uploadProgress"
                :on-success="editUploadSuccess"
                :on-error="euploadError"
                :file-list="editFiles"
                :show-file-list="true"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="editForm.categoryId" placeholder="请选择类别" @change="editCurrentSel">
                <el-option
                  v-for="item in categorys"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="4"></el-col>
          <el-col :span="20">
            <el-row :gutter="10">商品特性：</el-row>
            <el-row :gutter="10" v-for="(item,index) in editForm.categoryKeys" :key="index">
              <el-col :span="16">
                <el-form-item :label="item.value">
                  <el-select
                    v-model="editForm.productAttrs[item.value]"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请添加属性描述信息"
                  ></el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="商品详情" prop="detail">
              <el-input v-model="editForm.detail" auto-complete="off" class="form_input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog class="preview-modal" :visible.sync="dialogVisible" append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
  </section>
</template>

<script>
import util from "../../common/js/util";
import cfg from "../../cfg/const";
//provinces
//import NProgress from 'nprogress'
import {
  fetchProducts,
  addProduct,
  editProduct,
  removeProduct,
  batchRemoveProduct,
  getCityListPage,
  fetchCategorys,
  fetchAllCategorys
} from "../../api/api";

export default {
  data() {
    return {
      filters: {
        categoryId: undefined,
        isDisplay: undefined,
        productNo: undefined,
        name: undefined
      },
      displayOptions: cfg.displays,
      // citys: [],
      categorys: [], //分类下拉框初始化
      productAttrs: {}, //商品属性描述集合key+value,从服务器拉取
      currentCategoryId: 0, //当前商品的类型ID
      list: [],
      total: 0,
      currentPage: 1,
      listLoading: false,
      sels: [], //列表选中列
      mainImgFormVisible: false,
      mainImgSrc: "",
      subImgFormVisible: false,
      subImgSrc: [],

      //图片上传相关
      dialogImageUrl: "",
      dialogVisible: false,
      uploadComplete: true, // 图片上传完成状态
      isMainImage: false, //判断是不是首图
      editFiles: [], // 编辑时已上传图片初始化

      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: "名称", trigger: "blur" }],
        subTitle: [{ required: true, message: "标题", trigger: "blur" }],
        images: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        //origin: [{ required: true, message: "产地", trigger: "blur" }],
        //categoryId: [{ required: false, message: "分类", trigger: "blur" }],
        detail: [{ required: false, message: "详情", trigger: "blur" }]
      },

      //新增界面数据
      addForm: {
        name: "",
        subTitle: "",
        images: "",
        categoryId: "",
        detail: "",
        productAttrs: {},
        categoryKeys: []
      },

      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [{ required: true, message: "名称", trigger: "blur" }],
        subTitle: [{ required: true, message: "标题", trigger: "blur" }],
        images: [{ required: true, message: "图片", trigger: "blur" }],
        //origin: [{ required: true, message: "产地", trigger: "blur" }],
        categoryId: [{ required: true, message: "分类", trigger: "blur" }],
        // taste: [{ required: true, message: "口味", trigger: "blur" }],
        // pack: [{ required: true, message: "包装", trigger: "blur" }],
        detail: [{ required: false, message: "详情", trigger: "blur" }]
      },
      //编辑界面数据
      editForm: {
        productId: "",
        name: "",
        subTitle: "",
        images: "",
        categoryId: "",
        // origin: "",
        // taste: "",
        // pack: "",
        detail: "",
        productAttrs: {},
        categoryKeys: []
      }
    };
  },

  methods: {
    //商品分类下拉框选择处理 新增时
    currentSel(selVal) {
      let categoryKeys = [];
      let attrsObj = {};
      this.categorys.forEach(val => {
        if(selVal === val.id){
          categoryKeys = JSON.parse(val.keys);
        }
      });

      this.addForm.categoryKeys = categoryKeys;
      this.addForm.productAttrs = attrsObj;
      this.addForm.categoryId = selVal;
      console.log(attrsObj);
    },
    //商品下拉框选择
    editCurrentSel(selVal) {
      console.log("edit in");
      let categoryKeys = [];
      let attrsObj = {};
      this.categorys.forEach(val => {
        if(selVal === val.id){
          categoryKeys = JSON.parse(val.keys);
        }
      });
      categoryKeys.forEach(val => {
        console.log("now :",this.currentCategoryId," select : ",selVal);
        if ((this.currentCategoryId === selVal)) {
          console.log("only equal to origin come here~");
          attrsObj[val.value] = this.productAttrs[val.value]; //切换回编辑初始状态保留初始值
        } else {
          console.log("usually come here")
          attrsObj[val.value] = []; //切换别的分类需要重新录入属性值
        }
      });
      console.log("productAttr before change",this.editForm.productAttrs);
      this.editForm.productAttrs = attrsObj;
      console.log("productAttr after change",this.editForm.productAttrs);
      console.log("categoryKeys before change",this.editForm.categoryKeys);
      this.editForm.categoryKeys = categoryKeys;
      this.editForm.categoryId = selVal;
      console.log("categoryKeys after change",this.editForm.categoryKeys);
      console.log("edit out");
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    handleFilter() {
      if (isNaN(Number(this.filters.categoryId)) && this.filters.categoryId) {
        this.$message({
          message: "输入参数不是整数",
          type: "warning"
        });

        return;
      }

      this.getList();
    },
    showMainImg(src) {
      this.mainImgFormVisible = true;
      this.mainImgSrc = src;
    },
    showSubImg(src) {
      console.log(src);
      this.subImgFormVisible = true;
      this.subImgSrc = src.split(",");
    },
    //获取用户列表
    getList() {
      let _this = this;
      let filterMap = {
        categoryId: this.filters.categoryId
          ? Number(this.filters.categoryId)
          : undefined,
        productNo: this.filters.productNo
          ? Number(this.filters.productNo)
          : undefined,
        isDisplay:
          "" === this.filters.isDisplay ? undefined : this.filters.isDisplay,
        name: this.filters.name
      };
      let para = {
        currentPage: this.currentPage,
        productMap: encodeURIComponent(JSON.stringify(filterMap))
      };

      this.listLoading = true;
      //NProgress.start();
      fetchProducts(para).then(function(res) {
        console.log(res);
        _this.total = res.data.total;
        _this.list = res.data.products;
        _this.listLoading = false;
        //NProgress.done();
      });
    },
    //删除
    handleDel: function(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { data: { id: row.productId } };
          removeProduct(para).then(res => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function() {
      var ids = this.sels.map(item => item.productId);
      var idsStr = "";
      ids.forEach(function(val, index) {
        if (index == 0) {
          idsStr += val;
        } else {
          idsStr += "," + val;
        }
      });
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { data: { ids: idsStr } };
          batchRemoveProduct(para).then(res => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    //界面加载准备公用分类数据
    getCategorys: function() {
      fetchAllCategorys().then(res => {
        this.categorys = res.data;
      });
    },
    //显示新增界面
    handleAdd: function() {
      this.addFormVisible = true;

      this.addForm = {
        name: "",
        subTitle: "",
        mainImage: "",
        subImage: "",
        categoryId: "",
        detail: "",
        productAttrs: {},
        categoryKeys: []
      };
    },
    //新增
    addSubmit: function() {
      if (!this.uploadComplete) {
        this.$message.error("图片正在上传，请稍等");
        return;
      }
      console.log(this.addForm.categoryId);

      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            console.log(JSON.stringify(this.addForm.productAttrs));
            let para = Object.assign({}, this.addForm);
            let len = para.images.split(",").length;
            para.mainImage = len > 1 ? para.images.split(",")[0] : para.images; //主图url
            para.subImage = para.images;
            addProduct(para).then(res => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: "提交成功",
                type: "success"
              });
              this.$refs["addForm"].resetFields();
              this.addFormVisible = false;
              this.getList();
            });
          });
        }
      });
    },
    //显示编辑界面
    handleEdit: function(row) {
      this.editFormVisible = true;

      row.subTitle = row.title;
      let arr = row.subImage.split(",");
      let temp = [];
      arr.forEach(function(val, index) {
        temp.push({ name: "name" + index, url: val });
      });
      this.editFiles = temp;
      this.currentCategoryId = row.categoryId; //修改前保存当前商品分类
      this.productAttrs = row.attribute; //修改前的属性保存到data，类型切回或者取消提交可以找回
      this.editForm = Object.assign({}, row);
      this.editForm.images = row.subImage;

      this.categorys.forEach(val => {
        if (row.categoryId === val.id) {
          this.editForm.categoryKeys = JSON.parse(val.keys);
        }
      });

      this.editForm.productAttrs = row.attribute;
      console.log(this.editForm);
    },
    //编辑
    editSubmit: function() {
      if (!this.uploadComplete) {
        this.$message.error("图片正在上传，请稍等");
        return;
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            let len = para.images.split(",").length;
            para.mainImage = len > 1 ? para.images.split(",")[0] : para.images; //主图url
            para.subImage = para.images; //附图url 多个的话,逗号隔开
            console.log(para);
            editProduct(para).then(res => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: "提交成功",
                type: "success"
              });
              this.$refs["editForm"].resetFields();
              this.editFormVisible = false;
              this.getList();
            });
          });
        }
      });
    },

    // 上传图片前调用方法，新增和编辑公用
    beforeUploadPicture(file) {
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error("上传图片不能大于10M");
        return false;
      }
    },
    // 上传图片时调用,新增和编辑公用
    uploadProgress(event, file, fileList) {
      this.uploadComplete = false;
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      this.uploadComplete = true;
      this.fileChange(fileList);
    },
    // 上传图片出错,新增和编辑公用
    uploadError(err, file, fileList) {
      this.$message.error("上传出错");
    },
    // 移除图片
    handleRemove(file, fileList) {
      this.fileChange(fileList);
    },
    // 设置iamges值
    fileChange(fileList) {
      let temp_str = "";
      //console.log(fileList);
      if (fileList.length > 0) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) {
            if (fileList[i].response.code === 200) {
              if (i === 0) {
                temp_str += fileList[i].response.data;
              } else {
                // 最终photo的格式是所有已上传的图片的url拼接的字符串（逗号隔开）
                temp_str += "," + fileList[i].response.data;
              }
            }
          }
        }
      }
      this.addForm.images = temp_str;
      console.log(this.addForm.images);
    },

    //编辑表单中的上传相关操作

    // 上传图片成功
    editUploadSuccess(res, file, fileList) {
      this.uploadComplete = true;
      this.editFileChange(fileList);
    },
    // 移除图片
    editHandleRemove(file, fileList) {
      this.editFileChange(fileList);
    },
    // 设置images值
    editFileChange(fileList) {
      let temp_str = "";
      if (fileList.length > 0) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) {
            if (fileList[i].response.code === 200) {
              if (i === 0) {
                temp_str += fileList[i].response.data;
              } else {
                temp_str += "," + fileList[i].response.data;
              }
            }
          } else if (fileList[i].status && fileList[i].status === "success") {
            if (i === 0) {
              temp_str += fileList[i].url;
            } else {
              temp_str += "," + fileList[i].url;
            }
          }
        }
      }
      this.editForm.images = temp_str;
    },
    //图片预览拿出表单，新增和编辑公用
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  },
  mounted() {
    this.getList();
    this.getCategorys();
    // getCityListPage({
    // }).then(res => {
    //   this.citys = res.data.citys || res.data.data.citys;
    // });
  }
};
</script>

<style lang="scss" scoped>

</style>